package com.android.common.mvp.view.webview;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.webkit.DownloadListener;
import com.android.common.constant.Constant;

/**
 * 实现webview下载文件
 */
public class FileDownloadListener implements DownloadListener {
    private Context mContext;

    public FileDownloadListener(Activity context) {
        mContext = context;

    }

    @Override
    public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, final long contentLength) {
        Log.d("onDownloadStart", (String.format("url: %s, mimetype: %s, contentDisposition: %s, contentLength: %d", url, mimetype, contentDisposition, contentLength)));

//        Intent i = new Intent(mContext, DownloadActivity.class);
//        i.putExtra(DownloadActivity.EXTRA_URL, url);
//        i.putExtra(DownloadActivity.EXTRA_DISPOSITION, contentDisposition);
//        i.putExtra(DownloadActivity.EXTRA_MIMETYPE, mimetype);
//        i.putExtra(DownloadActivity.EXTRA_LENGTH, contentLength);
//        mContext.startActivity(i);
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addCategory(Intent.CATEGORY_BROWSABLE);
//        intent.setData(Uri.parse(url));
//        mContext.startActivity(intent);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.addRequestHeader(Constant.TOKEN_KEY,"bms_token_a2840957-32f4-4cb3-9792-44adba43a338");
        request.allowScanningByMediaScanner();
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "456.png");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        dm.enqueue(request);
        Intent pageView = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
        pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(pageView);

    }
}
